#!/usr/bin/env python
#coding=utf8

import requests
import time
from functools import wraps
import logging

from app.common.exception import ServiceError

class Connector(object):
    """
    定义连接器的基类
    """

    def __init__(self,client_id,secret_key,domain):
        self.client_id = client_id
        self.secret_key = secret_key
        self.domain = domain

    def packed_request(self, url, method, err_message, **kwargs):
        """发起连接，并且对连接进行异常判断
        1) 如果连接超时，则抛出异常
        2) 如果出现HTTP错误，则抛出异常
        3) 如果response包含'error'，则抛出异常
        4) 如果response不包含'data'，则抛出异常
        """
        try:
            response = requests.request(method, url, **kwargs)
        except requests.ConnectionError as e:
            logging.exception(self.__class__.__name__ + '服务不可用:' + str(e.message))
            raise ServiceError(message=self.__class__.__name__ + '服务不可用:' + str(e.message), \
                               connector_name=self.__class__.__name__)
        except requests.HTTPError as e:
            raise ServiceError(ext_error=e, message=err_message, \
                               connector_name=self.__class__.__name__)
        except Exception as e:
            raise ServiceError(message=str(e.message), connector_name=self.__class__.__name__)
        else:
            if response.status_code != 200:
                raise ServiceError(message=response.content, \
                                   connector_name=self.__class__.__name__)
            elif type(response.json()) == dict and response.json().has_key('error'):
                error = response.json()['error']
                raise ServiceError(message=err_message, ext_error=error, connector_name=self.__class__.__name__)
        return response
